#include "MiniMotor_Drv.h"

int EncoderSpeed =0;

void TIM8_Init(void)//20khz
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM8,ENABLE);
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct_TIM8;
	TIM_InternalClockConfig(TIM8);
	
	TIM_TimeBaseInitStruct_TIM8.TIM_ClockDivision =TIM_CKD_DIV1;
	TIM_TimeBaseInitStruct_TIM8.TIM_CounterMode =TIM_CounterMode_Up;
	TIM_TimeBaseInitStruct_TIM8.TIM_Period =600-1;//ARR
	TIM_TimeBaseInitStruct_TIM8.TIM_Prescaler =33-1;
	TIM_TimeBaseInitStruct_TIM8.TIM_RepetitionCounter =0;
	TIM_TimeBaseInit(TIM8,&TIM_TimeBaseInitStruct_TIM8);
	
	TIM_OCInitTypeDef TIM_OCInitStruct;
	TIM_OCInitStruct.TIM_OCIdleState =TIM_OCIdleState_Reset;
	TIM_OCInitStruct.TIM_OCMode =TIM_OCMode_PWM1;
	TIM_OCInitStruct.TIM_OCNIdleState =TIM_OCNIdleState_Set;
	TIM_OCInitStruct.TIM_OCNPolarity =TIM_OCNPolarity_Low;
	TIM_OCInitStruct.TIM_OCPolarity =TIM_OCPolarity_High;
	TIM_OCInitStruct.TIM_OutputNState =TIM_OutputNState_Disable;
	TIM_OCInitStruct.TIM_OutputState =TIM_OutputState_Enable;
	TIM_OCInitStruct.TIM_Pulse =0;
	TIM_OC1Init(TIM8,&TIM_OCInitStruct);
	TIM_OC2Init(TIM8,&TIM_OCInitStruct);
	
	TIM_OC1PreloadConfig(TIM8,TIM_OCPreload_Disable);
	TIM_OC2PreloadConfig(TIM8,TIM_OCPreload_Enable);
	
	TIM_ARRPreloadConfig(TIM8, ENABLE);
	TIM_Cmd(TIM8,ENABLE);
	TIM_CtrlPWMOutputs(TIM8,ENABLE);
}

void Motor_GoRight(void)
{
	GPIO_ResetBits(GPIOC,GPIO_Pin_5);
	GPIO_SetBits(GPIOC,GPIO_Pin_4);
}

void Motor_GoLeft(void)
{
	GPIO_ResetBits(GPIOC,GPIO_Pin_4);
	GPIO_SetBits(GPIOC,GPIO_Pin_5);
}

void Motor_Stop(void)
{
	GPIO_ResetBits(GPIOC,GPIO_Pin_4);
	GPIO_ResetBits(GPIOC,GPIO_Pin_5);
}

int16_t Encoder_GetValue(void)
{
	int16_t Temp;
	Temp = TIM_GetCounter(TIM3);
	TIM_SetCounter(TIM3, 0);
	return Temp;
}
